package scct.zhangyang.dao;

import scct.zhangyang.model.User;
import scct.zhangyang.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public User login(String name, String pass) {
        User user = null;
//        获取数据库连接对象
        Connection conn = DBUtils.getConnection();
        String sql = "select * from sm_user where username=? and password=?";
//        预编译查询对象
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, pass);
//            查询
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                int age = rs.getInt("age");
                String gender = rs.getString("gender");
                String mobile = rs.getString("mobile");
                user = new User(id, username, password, gender, age, mobile);
            }
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    public List<User> getAllUser() {
        Connection conn = DBUtils.getConnection();
        List<User> users = new ArrayList<>();
        String sql = "select * from sm_user";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                int age = rs.getInt("age");
                String gender = rs.getString("gender");
                String mobile = rs.getString("mobile");
                users.add(new User(id, username, password, gender, age, mobile));
            }
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return users;
    }
//    添加用户的方法
    public boolean addUser(String username,String password,String gender,int age,String monile){
        int result=0;
        Connection conn=DBUtils.getConnection();
        String insert_sql="insert into sm_user values(null,?,?,?,?,?)";
        try {
            PreparedStatement pstmt= conn.prepareStatement(insert_sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            pstmt.setString(3,gender);
            pstmt.setInt(4,age);
            pstmt.setString(5,monile);
            result=pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result==1;
    }
}

